/**
 * 用于解决以下两个场景
 * 
 * 1、运营商拦截、篡改内容导致页面加载异常
 * 
 * 2、识别IOS浏览器左划手势的后退功能 （此场景在微信上面不存在， 因为微信左划直接回到微信应用）;
 * @summary route 兼容方案
 * @author LinRenChen
 *
 * Created at     : 2018-09-09 03:50:50 
 * Last modified  : 2019-02-25 23:56:39
 */
import store from './../store';


/**
 * @param {router} 路由对象
 */
export default (router) => {
    const history = window.sessionStorage;
    history.clear();
    let historyCount = history.getItem('count') * 1 || 0;
    history.setItem('/', 0);
    let isPush = false;
    let endTime = Date.now();
    let methods = ['push', 'go', 'replace', 'forward', 'back'];

    document.addEventListener('touchend', () => {
        endTime = Date.now();
    });
    methods.forEach(key => {
        let method = router[key].bind(router);
        router[key] = function (...args) {
            isPush = true;
            method.apply(null, args);
        };
    });

    router.beforeEach(function (to, from, next) {
        store.commit('updateLoadingStatus', {
            isLoading: true
        });
 
        const toIndex = history.getItem(to.path);
        const fromIndex = history.getItem(from.path);

        if (toIndex) {
            if (!fromIndex || parseInt(toIndex, 10) > parseInt(fromIndex, 10) || (toIndex === '0' && fromIndex === '0')) {
                store.commit('updateDirection', {
                    direction: 'forward'
                });
            } else {
                // 判断是否是ios左滑返回
                if (!isPush && (Date.now() - endTime) < 377) {
                    store.commit('updateDirection', {
                        direction: ''
                    });
                } else {
                    store.commit('updateDirection', {
                        direction: 'reverse'
                    });
                }
            }
        } else {
            ++historyCount;
            history.setItem('count', historyCount);
            to.path !== '/' && history.setItem(to.path, historyCount);
            store.commit('updateDirection', {
                direction: 'forward'
            });
        }
        
        if (/\/http/.test(to.path)) {
            let url = to.path.split('http')[1];
            window.location.href = `http${url}`;
        } else {
            next();
        }
    });

    router.afterEach(function () {
        isPush = false;
        store.commit('updateLoadingStatus', {
            isLoading: false
        });
    });
}